import type { RequestConfig } from '@minmetals/request';
import { HeaderConfig } from '@minmetals/auth-lib';
import { logout } from '@minmetals/common-lib';
import { Http } from '@minmetals/request';
import { ElMessage } from 'element-plus-cisdi';

function toLoginPage() {
  logout();
}

// 自定义请求拦截器
function requestInterceptor(config: RequestConfig) {
  Object.assign(config.headers ?? {}, HeaderConfig.init().getHeaderConfig());
  return config;
}

// 自定义响应拦截器
function responseInterceptor(response: any) {
  if (response.code === '0') {
    return Promise.resolve(response);
  } else {
    ElMessage.error(response.message);
    return Promise.reject(response);
  }
}
/**
 * 用于基础服务平台新接口请求
 */
const http = new Http({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  logout: toLoginPage,
  interceptors: { requestInterceptor, responseInterceptor },
  // 自定义处理错误响应的函数
  customHandleErrorResponse: errorResponse =>
    ElMessage.error(errorResponse.message),
});
/**
 * 语言包的请求
 */
export const langHttp = new Http({
  baseURL: '/',
  appId: 'app-cisdigital-lingshu-language',
  logout: toLoginPage,
  interceptors: { requestInterceptor, responseInterceptor },
  customHandleErrorResponse: errorResponse =>
    ElMessage.error(errorResponse.message),
});

export default http;
